package com.avicsafety.lib.PhotoManager;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.avicsafety.lib.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class PhotoListActivity extends Activity implements OnClickListener {

    private GridView grid_view;
    private Button btn_photo_list_submit;
    private Button btn_photo_list_take_photo;
    private Button btn_photo_list_history_photo;
    private Button btn_photo_list_delete;
    private TextView tv_photo_list_back;
    private TextView tv_photo_list_title;
    private File tempFile;
    private String newFilePath = "";
    private String DEFAULT_PATH = "";
    private List<String> mData = new ArrayList<String>();
    private List<String> selectedData = new ArrayList<String>();
    private boolean hasData = false;
    private int max = 0;
    private int min = 0;
    private boolean historicalPictures = false;//用于判断界面显示历史图片或者图片管理 2018.1.23
    private int ishistory = 0;//传递的参数如果1则只显示历史图片,2则只显示图片管理,任意数为可切换状态

    //private String[] mData = new ArrayList<>();

    private final int PHOTO_REQUEST_TAKEPHOTO = 90000;
    private final int PHOTO_REQUEST_CUT = 90001;

    private static final String[] STORE_IMAGES = {
            MediaStore.Images.Thumbnails.DATA
    };
    private PhotoAdapter photoAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_com_avicsafety_photo_photomanager_photo_list);

        if (android.os.Build.VERSION.SDK_INT >= 20) {
            DEFAULT_PATH = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
        } else {
            DEFAULT_PATH = Environment.getExternalStorageDirectory()
                    + File.separator + this.getPackageName()
                    + File.separator + "Pictures";
        }

        grid_view = (GridView) this.findViewById(R.id.grid_view);
        btn_photo_list_submit = (Button) this.findViewById(R.id.btn_photo_list_submit);
        btn_photo_list_take_photo = (Button) this.findViewById(R.id.btn_photo_list_take_photo);
        btn_photo_list_history_photo = (Button) this.findViewById(R.id.btn_photo_list_history_photo);
        tv_photo_list_back = (TextView) this.findViewById(R.id.tv_photo_list_back);
        //btn_photo_list_delete = (Button) this.findViewById(R.id.btn_photo_list_delete);
        tv_photo_list_title = (TextView) this.findViewById(R.id.tv_photo_list_title);
        init();

        photoAdapter = new PhotoAdapter(this, mData, selectedData, R.layout.item_com_avicsafety_photo_photomanager_photo, "");
        grid_view.setAdapter(photoAdapter);
        btn_photo_list_take_photo.setOnClickListener(this);
        btn_photo_list_history_photo.setOnClickListener(this);
        tv_photo_list_back.setOnClickListener(this);
        //btn_photo_list_delete.setOnClickListener(this);
        btn_photo_list_submit.setOnClickListener(this);

        //this Directory already created;
//		File path = new File(DEFAULT_PATH);
//		if(!path.exists()){
//			path.mkdir();
//		}
    }

    private void init() {

        // 指定调用相机拍照后照片的储存路径
        File dir = new File(DEFAULT_PATH);
        if (!dir.exists()) {
            dir.mkdir();
        }
        tempFile = new File(dir + File.separator + "temp.jpg");
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            ishistory = bundle.getInt("ishistory");
        }
        if (ishistory == 1) {
            btn_photo_list_history_photo.setVisibility(View.GONE);
            historicalPictures = true;
        } else if (ishistory == 2) {
            historicalPictures = false;
            btn_photo_list_history_photo.setVisibility(View.GONE);
        }
        if (bundle == null) {
            getData();
        } else {
            String[] data = bundle.getStringArray("data");
            List<String> list = getIntent().getStringArrayListExtra("list");
            //String path =  bundle.getString("path","");
            //废弃参数path传递， 系统会自动找到 Android/data/包名/files/Pictures 为保存目录
            String title = bundle.getString("title", "图片管理");
            boolean readonly = bundle.getBoolean("readonly", false);
            max = bundle.getInt("max", 0);
            min = bundle.getInt("min", 0);

            tv_photo_list_title.setText(title);

            if (data != null) {
                fromArrayToCollection(data, selectedData);
            }

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    selectedData.add(list.get(i));
                }
            }
            if (readonly) {
                btn_photo_list_take_photo.setVisibility(View.GONE);
//				btn_photo_list_delete.setVisibility(View.GONE);
                btn_photo_list_submit.setVisibility(View.GONE);
                mData.clear();
                for (int i = 0; i < selectedData.size(); i++) {
                    mData.add(selectedData.get(i));
                }
            }
            if (historicalPictures) {
                getHistoryData();
            } else {
                getData();
            }
        }
    }

    private void getData() {
        mData.clear();
        String selection = MediaStore.Images.Media.DATA + " like '" + DEFAULT_PATH + "%'";
        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STORE_IMAGES, selection, null, MediaStore.Images.Media.DATE_ADDED + " desc");
        while (cursor.moveToNext()) {
            String strValue = cursor.getString(0);

            File image_file = new File(strValue);
            if (!image_file.exists()) {
                this.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Thumbnails.DATA + "=?", new String[]{strValue});
            } else {
                if (!strValue.contains("temp.jpg")) {
                    mData.add(strValue);
                }

            }
        }
        cursor.close();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.btn_photo_list_take_photo) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1000);
            } else {
                OpenCamera();
            }
        } else if (v.getId() == R.id.btn_photo_list_submit) {
            boolean flag = true;
            if (min != 0 && photoAdapter.getSelectedImage().size() < min) {
                Toast.makeText(this, "最少选择" + min + "张图片", Toast.LENGTH_LONG).show();
                flag = false;
            }
            if (max != 0 && photoAdapter.getSelectedImage().size() > max) {
                Toast.makeText(this, "选择的图片不可以超过" + max + "张", Toast.LENGTH_LONG).show();
                flag = false;
            }
            if (flag) {
                Intent intent = new Intent();
                if (photoAdapter.getSelectedImage().size() > 0) {
                    List<String> list = photoAdapter.getSelectedImage();
                    String[] array = new String[list.size()];
                    list.toArray(array);
                    Bundle bundle = new Bundle();
                    bundle.putStringArray("result", array);
                    bundle.putStringArrayList("result_list", (ArrayList<String>) list);
                    intent.putExtras(bundle);
                    this.setResult(RESULT_OK, intent);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putStringArray("result", new String[]{});
                    bundle.putStringArrayList("result_list", new ArrayList<String>());
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                }
                Log.v("tag", "getSelectedImage is " + photoAdapter.getSelectedImage().size());
                finish();
            }
        } else if (v.getId() == R.id.tv_photo_list_back) {
            this.setResult(RESULT_CANCELED);
            finish();
        } else if (v.getId() == R.id.btn_photo_list_history_photo) {
            historicalPictures = !historicalPictures;
            if (historicalPictures) {
                tv_photo_list_title.setText("历史图片");
                btn_photo_list_history_photo.setText("图片管理");
            } else {
                btn_photo_list_history_photo.setText("历史图片");
            }
            init();
            photoAdapter.notifyDataSetChanged();
        }
    }

    //	private void OpenCamera() {
    //		Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //		Uri photoURI = getUriByFile(tempFile);
    //		grantUriPermission("com.android.camera",photoURI,
    //				Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    //		cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
    //		cameraintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    //		cameraintent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    //		startActivityForResult(cameraintent, PHOTO_REQUEST_TAKEPHOTO);
    //	}
    private void OpenCamera() {
        Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri photoURI = getUriByFile(tempFile);
        grantUriPermission("com.android.camera", photoURI,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        cameraintent.putExtra(MediaStore.EXTRA_OUTPUT, processingImages());
        cameraintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        cameraintent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(cameraintent, PHOTO_REQUEST_CUT);
    }

    /**
     * 处理图片
     *
     * @return Uri
     */
    private Uri processingImages() {
        //生成一个随机文件
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String str = simpleDateFormat.format(new Date());
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
        File dir = new File(DEFAULT_PATH);
        newFilePath = dir + File.separator + str + rannum + ".jpg";

        //插入到系统库
        ContentValues values = new ContentValues();
        values.put(Media.DATA, newFilePath);
        values.put(Media.TITLE, str + rannum + ".jpg");
        Log.v("tag", newFilePath);
        this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        return  getUriByFile(new File(newFilePath));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1000: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    OpenCamera();
                } else {
                    Toast.makeText(this, "因为未授权所以无法打开相机", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PHOTO_REQUEST_TAKEPHOTO:// 当选择拍照时调用
                if (resultCode == RESULT_OK) {
                    File dir = new File(DEFAULT_PATH);
                    tempFile = new File(dir + File.separator + "temp.jpg");
                    Uri photoURI = getUriByFile(tempFile);
                    grantUriPermission("com.android.camera", photoURI,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    startPhotoZoom(photoURI);
                }
                break;
            case PHOTO_REQUEST_CUT:// 返回的结果
                if (resultCode == RESULT_OK) {
                    proportionCompressImage(newFilePath);
                    photoAdapter.addSelectedImage(newFilePath);
                } else {
                    getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Thumbnails.DATA + "=?", new String[]{newFilePath});
                }
                getData();
                photoAdapter.notifyDataSetChanged();
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //intent.setDataAndType(uri, "image/*");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);

        //生成一个随机文件
        SimpleDateFormat simpleDateFormat;
        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String str = simpleDateFormat.format(date);
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
        File dir = new File(DEFAULT_PATH);
        newFilePath = new String(dir + File.separator + str + rannum + ".jpg");

        //插入到系统库
        ContentValues values = new ContentValues();
        values.put(Media.DATA, newFilePath);
        values.put(Media.TITLE, str + rannum + ".jpg");
        Log.v("tag", newFilePath);
        this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        //打开
        Uri photoURI = Uri.fromFile(new File(newFilePath));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    /**
     * 删除图片
     *
     * @param selectedImage
     */
    private void deleteAll(final List<String> selectedImage) {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Confirm")
                .setMessage("真的要删除这些图片吗?")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        for (String path : selectedImage) {
                            getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Thumbnails.DATA + "=?", new String[]{path});
                            File file = new File(path);
                            file.delete();
                        }
                        photoAdapter.getSelectedImage().clear();
                        getData();
                        photoAdapter.notifyDataSetChanged();

                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putStringArray("result", new String[]{});
                        intent.putExtras(bundle);
                        setResult(RESULT_OK, intent);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 从sd卡获取历史图片资源
     *
     * @return
     */
    private void getHistoryData() {
        String TEMP_PATH;
        if (android.os.Build.VERSION.SDK_INT >= 20) {
            TEMP_PATH = getExternalFilesDir(Environment.DIRECTORY_MUSIC).getAbsolutePath();
        } else {
            TEMP_PATH = Environment.getExternalStorageDirectory()
                    + File.separator + this.getPackageName()
                    + File.separator + "Music";
        }
        mData.clear();
        File fileAll = new File(TEMP_PATH);
        File[] files = fileAll.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            mData.add(file.getPath());
        }
    }

    /**
     * 按比例压缩图片
     *
     * @param srcPath
     * @return String
     */
    private String proportionCompressImage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 1024f;//这里设置高度为1024f
        float ww = 768f;//这里设置宽度为768f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return qualityCompressImage(bitmap);
    }

    /**
     * 按质量压缩图片
     *
     * @param image
     * @return String
     */
    private String qualityCompressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return saveBitmap(bitmap);
    }

    /**
     * 保存bitmap到本地,返回图片路径
     *
     * @param mBitmap
     * @return String
     */
    public String saveBitmap(Bitmap mBitmap) {
        File filePic = new File(newFilePath);
        try {
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(newFilePath);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return filePic.getAbsolutePath();
    }

    //	@Override
//	public void onScrollStateChanged(AbsListView view, int scrollState) {
//		// TODO Auto-generated method stub
//		switch (scrollState){  
//		  
//        case AbsListView.OnScrollListener.SCROLL_STATE_IDLE://停止滚动  
//            //设置为停止滚动  
//        	photoAdapter.setScrollState(false);  
//        	int count = view.getChildCount();  
//
//            for (int i = 0; i < count; i++) {  
//                //获取到item的name  
//            	 ImageView iv_show = (ImageView) view.getChildAt(i).findViewById(R.id.iv_photo_list_item);  
//            	Log.v("photo", i+" is "+ iv_show.getTag().toString());
//               
//                if (!iv_show.getTag().equals("1")){//!="1"说明需要加载数据  
//                	ImageLoader.getInstance().displayImage(iv_show.getTag().toString(), iv_show);
//                    iv_show.setTag("1");//设置为已加载过数据  
//                }  
//            }  
//            break;  
//        case AbsListView.OnScrollListener.SCROLL_STATE_FLING://滚动做出了抛的动作  
//        	//设置为正在滚动  
//        	photoAdapter.setScrollState(true);  
//            break;  
//
//        case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL://正在滚动  
//            //设置为正在滚动  
//        	photoAdapter.setScrollState(true);  
//            break;  
//    }  
//	}

//	@Override
//	public void onScroll(AbsListView view, int firstVisibleItem,
//			int visibleItemCount, int totalItemCount) {
//		// TODO Auto-generated method stub
//		
//	}

    private Uri getUriByFile(File file) {
        Uri photoURI;
        if (android.os.Build.VERSION.SDK_INT >= 24) {
            photoURI = FileProvider.getUriForFile(this, this.getPackageName(), file);
        } else {
            photoURI = Uri.fromFile(file);
        }
        return photoURI;
    }

    static <T> void fromArrayToCollection(T[] array, Collection<T> b) {
        for (T str : array) {
            b.add(str);
        }
    }
}
